#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;

class Trie {
private:
    std::unordered_map<wchar_t, Trie*> childrens;
    bool is_end;
public:
    Trie() {
        childrens.clear();
        is_end = false;
    }

    void insert(string word) {
        Trie* node = this;
        for (wchar_t  c : word)
        {
            auto it = node->childrens.find(c);
            if (it == node->childrens.end()) node->childrens[c] = new Trie();
            node = node->childrens[c];
        }

        node->is_end = true;
    }

    bool search(string word) {
        Trie* node = this;
        for (wchar_t c : word)
        {
            auto it = node->childrens.find(c);
            if (it == node->childrens.end()) return false;
            node = node->childrens[c];
        }
        return node->is_end;
    }

    bool startsWith(string prefix) {
        Trie* node = this;
        for (wchar_t  c : prefix)
        {
            auto it = node->childrens.find(c);
            if (it == node->childrens.end()) return false;
            node = node->childrens[c];
        }

        return true;
    }

    std::vector<string> showStartsWith(string prefix)
    {
        Trie* node = this;
        for (wchar_t  c : prefix)
        {
            auto it = node->childrens.find(c);
            if (it == node->childrens.end()) return {};
            node = node->childrens[c];
        }

        std::vector<string> res;
        res.clear();
        string path = "";
        path+=prefix;
        this->backcall(node, res, path);
        return res;
    }
private:
    void backcall(Trie* cur, std::vector<string>& res, string& path)
    {
        if (nullptr == cur)  return;
        
        if (cur->is_end)
        {
            res.push_back(path);
            return;
        }

        //遍历全部
        for (auto it : cur->childrens)
        {
            path.push_back(it.first);
            this->backcall(it.second, res, path);
            path.pop_back();
        }
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

int main()
{
    Trie* obj = new Trie();
    obj->insert("张三");
    obj->insert("张无");
    obj->insert("张九龙");
    obj->insert("张一二");
    obj->insert("张一是·");

    //
    std::vector<string> res = obj->showStartsWith("张一");
    
    {
        for (auto s : res)
        {
            cout << s << endl;
        }
    }
    return 0;
}